package app.android.com.wuandroidapp.test.view.fragment;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;


import java.util.ArrayList;
import java.util.List;

import app.android.com.utilscode.util.ImageUtils;
import app.android.com.wuandroidapp.AndroidApplication;
import app.android.com.wuandroidapp.R;
import app.android.com.wuandroidapp.library.fragment.BaseFragment;
import app.android.com.wuandroidapp.test.model.db.entities.minimalist.Data;
import app.android.com.wuandroidapp.test.model.db.entities.minimalist.FaceMapModel;
import app.android.com.wuandroidapp.test.model.db.entities.minimalist.HelpPromodtionDetail;
import app.android.com.wuandroidapp.test.model.http.HttpService;
import app.android.com.wuandroidapp.test.model.http.OKCallBack;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends BaseFragment {


    private static String usnames;
    Unbinder unbinder;
    @BindView(R.id.baidu_map)
    MapView baiduMap;

    BaiduMap mBaiduMap;
    String ids;


    public final String ONE = "1";
    public final String TWO = "2";
    public final String THREE = "3";
    public final String FOUR = "4";
    public final String FIVE = "5";

    public HomeFragment() {
        // Required empty public constructor
    }

    public static HomeFragment newInstance(String username) {
        usnames = username;
        return new HomeFragment();
    }


    View currentView;
    int CHILD_COUNT;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_home, container, false);

        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mBaiduMap = baiduMap.getMap();
        getbaimap();
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {

            @Override
            public boolean onMarkerClick(Marker marker) {

                marker.setToTop();
                ids = marker.getTitle();
                int id = Integer.parseInt(ids);
                FaceMapModel mapModel = mapModels.get(id);
                //       ToastUtil.showMessage(mapModel.getId());
                getpopwindow(mapModel);
                return false;
            }
        });
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                ll_pop.setVisibility(View.GONE);
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });
        /**
         * 地图状态发生变化
         */
        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            public void onMapStatusChangeStart(MapStatus status) {
                //     updateMapState();
            }

            public void onMapStatusChangeFinish(MapStatus status) {
                //          updateMapState();
            }

            public void onMapStatusChange(MapStatus status) {
                //      updateMapState();
            }
        });

        initpopwoind();
    }

    float zoom = 18;

    /**
     * 更新地图状态显示面板
     */
    private void updateMapState() {
        ll_pop.setVisibility(View.GONE);
        String state = "";

        state += "\n";
        MapStatus ms = mBaiduMap.getMapStatus();
        state += String.format(
                "zoom=%.1f rotate=%d overlook=%d",
                ms.zoom, (int) ms.rotate, (int) ms.overlook);

        if (ms.zoom <= 10.0) {
            if (DistanceUtil.getDistance(p, ms.target) > 50000 | zoom != ms.zoom) {
                p = ms.target;
                la = p.latitude + "";
                lo = p.longitude + "";
                zoom = ms.zoom;
                mapModels.clear();
                getmapService(FIVE, city, la, lo);
            }
        }
        if (ms.zoom <= 13.0 && ms.zoom > 10.0) {
            if (DistanceUtil.getDistance(p, ms.target) > 10000 | zoom != ms.zoom) {
                mapModels.clear();
                getmapService(FIVE, city, la, lo);
            }
        }
        if (ms.zoom > 17.0) {
            if (DistanceUtil.getDistance(p, ms.target) > 500 | zoom != ms.zoom) {
                p = ms.target;
                la = p.latitude + "";
                lo = p.longitude + "";
                zoom = ms.zoom;
                mapModels.clear();
                getmapService(ONE, city, la, lo);
            }
        }
        if (ms.zoom <= 17.0 && ms.zoom > 15.0) {
            if (DistanceUtil.getDistance(p, ms.target) > 1000 | zoom != ms.zoom) {
                p = ms.target;
                la = p.latitude + "";
                lo = p.longitude + "";
                zoom = ms.zoom;
                mapModels.clear();
                getmapService(TWO, city, la, lo);
            }
        }
        if (ms.zoom <= 15.0 && ms.zoom > 13.0) {
            if (DistanceUtil.getDistance(p, ms.target) > 5000 | zoom != ms.zoom) {
                p = ms.target;
                la = p.latitude + "";
                lo = p.longitude + "";
                zoom = ms.zoom;
                mapModels.clear();
                getmapService(THREE, city, la, lo);
            }
        }

        Log.e("location", state);

    }

    LatLng p;
    String city;
    String la;
    String lo;
    BDLocation location;

    public void getbaimap() {
        if (p != null) {
            updateMapState();
        } else {
            if (AndroidApplication.getInstance().locations != null) {

                getlocs(AndroidApplication.getInstance().locations);
            } else {
                AndroidApplication.getInstance().mLocationClient.registerLocationListener(new BDLocationListener() {
                    @Override
                    public void onReceiveLocation(BDLocation location) {
                        getlocs(location);
                    }

                    @Override
                    public void onConnectHotSpotMessage(String s, int i) {

                    }
                });
            }
        }

    }

    public void getlocs(BDLocation location) {
        location = AndroidApplication.getInstance().locations;
        p = new LatLng(location.getLatitude(), location.getLongitude());
        MapStatus mMapStatus = new MapStatus.Builder()
                .target(p)
                .zoom(18)
                .build();
        city = location.getCity();
        la = location.getLatitude() + "";
        lo = location.getLongitude() + "";
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        //改变地图状态
        mBaiduMap.setMapStatus(mMapStatusUpdate);
        mBaiduMap.animateMapStatus(mMapStatusUpdate);
        getmapService(ONE, location.getCity(), location.getLatitude() + "", location.getLongitude() + "");

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        baiduMap.onDestroy();
        unbinder.unbind();
    }

    List<FaceMapModel> mapModels = new ArrayList<>();

    boolean ismap = true;

    public void getmapService(String d, String city, String place_la, String place_lo) {
        if (ismap) {
            ismap = false;

            for (int i = 0; i < 5; i++) {
                FaceMapModel faceMapModel = new FaceMapModel();
                faceMapModel.setPlace_la((Double.parseDouble(la) + i * 0.001) + "");
                faceMapModel.setPlace_lo((Double.parseDouble(lo) + i * 0.001) + "");
                faceMapModel.setName("女皇护卫");
                faceMapModel.setContent("为皇女殿下效力");
                mapModels.add(faceMapModel);
            }
            for (int i = 0; i < 5; i++) {
                FaceMapModel faceMapModel = new FaceMapModel();
                faceMapModel.setPlace_la((Double.parseDouble(la) - i * 0.001) + "");
                faceMapModel.setPlace_lo((Double.parseDouble(lo)) + "");
                faceMapModel.setName("女皇护卫");
                faceMapModel.setContent("为皇女殿下效力");
                mapModels.add(faceMapModel);
            }
            handler.sendEmptyMessageAtTime(200, 50);
        }
    }

    ArrayList<MarkerOptions> marks = new ArrayList<>();

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 200:
                    ismap = true;
                    //     LocationUtil.getInstance().stop();
                    //通过系统提供的实例获得一个LayoutInflater对象
                    mBaiduMap.clear();
                    LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    final MapStatus ms = mBaiduMap.getMapStatus();
                     View views = inflater.inflate(R.layout.view_photo, null);
             //       ImageView imgeview = (ImageView) views.findViewById(R.id.view_photo);
//                    BitmapDescriptor bdGround = BitmapDescriptorFactory
//                            .fromView(views);
                    BitmapDescriptor bdGround = BitmapDescriptorFactory.fromResource(R.mipmap.ic_ovlay_photo);

                    if (mapModels.size() > 0) {
                        for (int i = 0; i < mapModels.size(); i++) {
                            //第一个参数为xml文件中view的id，第二个参数为此view的父组件，可以为null，android会自动寻找它是否拥有父组件

                            final FaceMapModel mapModel = mapModels.get(i);
                            final String modelsi = i + "";

                            //在这里面调用百度地图api

                            double la = Double.parseDouble(mapModel.getPlace_la());
                            double lo = Double.parseDouble(mapModel.getPlace_lo());

                            LatLng p1 = new LatLng(la, lo);
                            MarkerOptions op = new MarkerOptions()
                                    .position(p1)
                                    .title(modelsi)
                                    .icon(bdGround);

                            marks.add(op);
                            for (int j = 0; j < marks.size(); j++) {

                                mBaiduMap.addOverlay(marks.get(j));
                            }
                            MapStatus mMapStatus = new MapStatus.Builder()
                                    .target(p)
                                    .zoom(ms.zoom)
                                    .build();
                            MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
                            //改变地图状态
                            mBaiduMap.setMapStatus(mMapStatusUpdate);
                            mBaiduMap.animateMapStatus(mMapStatusUpdate);

                        }
                    }
                    break;
                case 400:
                    ismap = true;
                    //      LocationUtil.getInstance().stop();
                    break;
            }
        }
    };


    LinearLayout ll_pop;
    ImageView iv_face_avatar;
    TextView tv_name;
    TextView tv_moneys;
    TextView tv_title, tv_content;

    float mPosX;
    float mPosY;

    float mCurPosX;
    float mCurPosY;
    LinearLayout ll_1;
    RelativeLayout rl_56;

    public void initpopwoind() {
        ll_pop = (LinearLayout) getActivity().findViewById(R.id.ll_pop);
        ll_pop.setVisibility(View.GONE);
        ll_1 = (LinearLayout) getActivity().findViewById(R.id.ll_1);
        rl_56 = (RelativeLayout) getActivity().findViewById(R.id.rl_56);
        iv_face_avatar = (ImageView) getActivity().findViewById(R.id.iv_face_avatar);
        tv_name = (TextView) getActivity().findViewById(R.id.tv_name);
        tv_title = (TextView) getActivity().findViewById(R.id.tv_title);
        tv_content = (TextView) getActivity().findViewById(R.id.tv_content);


    }

    public void getpopwindow(final FaceMapModel mapModel) {
        ll_pop.setVisibility(View.VISIBLE);
        ll_pop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //      startActivity(new Intent(getActivity(), FaceDetailActivity.class).putExtra("id", mapModel.getId()));
            }
        });


        iv_face_avatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        //      ImageUtils.setHeadImage(mapModel.getPhoto(), iv_face_avatar);
        tv_name.setText(mapModel.getName());
        tv_content.setText(mapModel.getContent());

        ll_pop.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                switch (event.getAction()) {

                    case MotionEvent.ACTION_DOWN:
                        mPosX = event.getX();
                        mPosY = event.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:

                        break;
                    case MotionEvent.ACTION_UP:
                        mCurPosX = event.getX();
                        mCurPosY = event.getY();
                        if (mCurPosX - mPosX > 0
                                && (Math.abs(mCurPosX - mPosX) > 45)) {
                            int id = Integer.parseInt(ids);
                            id--;
                            if (id == -1) {
                                id = mapModels.size() - 1;
                            }
                            getpopwindow(mapModels.get(id));
                            ids = id + "";
                            getRight();
                            return true;
                        } else if (mCurPosX - mPosX < 0
                                && (Math.abs(mCurPosX - mPosX) > 45)) {
                            int id = Integer.parseInt(ids);
                            id++;
                            if (id == mapModels.size() - 1) {
                                id = 0;
                            }
                            if (id == mapModels.size()) {
                                id = 0;
                            }

                            getpopwindow(mapModels.get(id));

                            ids = id + "";
                            getLeft();
                            return true;
                        }
                        break;
                }
                return false;
            }

        });
    }

    public void getRight() {
        //向右滑動
        //    ToastUtil.showMessage("向右滑動");
        // XML文件
        Animation animations = AnimationUtils.loadAnimation(getActivity(),
                R.anim.translate_demo2);

        animations.setRepeatCount(0);//循环显示

        animations.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                ll_pop.clearAnimation();
                Animation animationc = AnimationUtils.loadAnimation(getActivity(),
                        R.anim.translate_right2);
                animationc.setRepeatCount(0);//循环显示
                ll_pop.startAnimation(animationc);
                animationc.startNow();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        ll_pop.startAnimation(animations);
        animations.startNow();
    }

    public void getLeft() {
        //向左滑动
        //   ToastUtil.showMessage("向左滑动");
        // XML文件
        Animation animations = AnimationUtils.loadAnimation(getActivity(),
                R.anim.translate_demo);

        animations.setRepeatCount(0);//循环显示

        animations.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                ll_pop.clearAnimation();
                Animation animationc = AnimationUtils.loadAnimation(getActivity(),
                        R.anim.translate_right);
                animationc.setRepeatCount(0);//循环显示
                ll_pop.startAnimation(animationc);
                animationc.startNow();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        ll_pop.startAnimation(animations);
        animations.startNow();
    }

    @Override
    public void onResume() {
        super.onResume();
        //     baiduMap.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        baiduMap.onDestroy();
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        //    baiduMap.onPause();
    }

}
